<!-- 新建样品组件 -->
<template>
	<view style="width: 100%; background-color: #fff;padding: 20rpx;">
		<!-- 引入公共头部组件 -->
		<HeaderTitle title="新建样品" :rightContent="rightContent" @selectRightIconChange="selectRightIconChange"
			:isBack="true" :isSearch="false" rightTextColor="#1989FA" />

		<uni-forms ref="form" :modelValue="entity" label-width="100px">
			<view class="client" style="padding-bottom:67px;">
				<uni-forms-item label="客户名称：" placeholder="请选择客户" v-model="entity.CustomerName"
					:rules="$rules.handle.CustomerName" required name="CustomerName">
					<view @click="CustomerChoice">
						<uni-easyinput v-model="entity.CustomerName" placeholder="请选择客户" suffixIcon="compose"
							:disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="申请日期：">
					<view @click="isCalendar=true">
						<uni-easyinput v-model="entity.ApplyDate" placeholder="请选择申请日期" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="收件人：" :rules="$rules.handle.Addressee" required name="Addressee">
					<view @click="showPickerClick">
						<uni-easyinput v-model="entity.Addressee" placeholder="请选择收件人" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="经办人：">
					<uni-data-select v-model="entity.RealName" :localdata="columnsRealName"
						placeholder="请选择经办人"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="紧急程度：">
					<view>
						<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
							placeholder="紧急程度" v-model="entity.Urgency" :localdata="UrgencyOptions"
							@change="UrgencyOptionsChange"></uni-data-select>
					</view>
				</uni-forms-item>
				<uni-forms-item label="样品用途：">
					<view>
						<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
							placeholder="样品用途" v-model="entity.Purpose" :localdata="PurposeOptions"></uni-data-select>
					</view>
				</uni-forms-item>
				<uni-forms-item label="收件电话：" :rules="$rules.handle.AddresseeTel" required name="AddresseeTel">
					<view>
						<uni-easyinput v-model="entity.AddresseeTel" placeholder="收件电话" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="收货地址：" :rules="$rules.handle.ReceiveAddress" required name="ReceiveAddress">
					<view>
						<uni-easyinput v-model="entity.ReceiveAddress" placeholder="收货地址" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="试用说明：">
					<view>
						<uni-easyinput v-model="entity.SampleTrialRemark" placeholder="试用说明" type="textarea" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="备注：">
					<view>
						<uni-easyinput v-model="entity.Remark" placeholder="备注" type="textarea" />
					</view>
				</uni-forms-item>


				<view class="scrollBox">
					<scroll-view style="width: 100%;height: 100%;" scroll-y="true">
						<view style="padding-bottom: 50px;">
							<view class=" " v-for="(item, index) in data" :key="item.Id" style=" width: 93%;
						      margin: 0 auto;
						      box-shadow: 3px 4px 16px 0px #6b6b6a;
						      margin-top: 20px;
						      margin-bottom: 10px;
						      background-color: #ffffff;
						      border-radius: 5px;
						      padding-top: 1px;
						      padding-bottom: 4px;
						    ">
								<view class="left" style="font-size: 14px; color: #000">
									品名:<span class="font">{{ item.ProductId }}/{{ item.cInvName }}</span>
								</view>
								<view class="left" style="font-size: 14px">
									规格:<span class="font">{{ item.cInvStd || "无" }}</span>
								</view>
								<view class="Fa">
									<span class="left" style="font-size: 14px">数量:</span>
									<u-number-box style="margin-left: 30rpx;"
										v-model="item.MainQuantity"></u-number-box>
								</view>
								<view style="display: flex;padding: 0 30rpx;">
									<span style="padding-top: 10rpx;">备注：</span>
									<uni-easyinput v-model="item.Remark" placeholder="备注" :inputBorder="false" />
								</view>

								<view class="delete-list">
									<view @click="delte([item.Id], index)" style="
						          width: 15%;
						          border-radius: 5px;
						          line-height: 30px;
						          color: #fff;
						          text-align: center;
						          background-color: red;
						        ">
										删除
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<div class="submitButton">
					<button v-show="hideshow" class="button" @click="AddProduct" :loading="loading">添加产品</button>
					<u-button type="primary" style="font-size: 14px;margin-top: 20rpx;" @click="onSubmit"
						:loading="loading">提交</u-button>
				</div>

			</view>
		</uni-forms>
		<!-- 选择客户 -->
		<Myuser ref="myuser" @customerChoice="Client" />
		<!-- 添加产品 -->
		<Product ref="product" @Product="Product" />
		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期"></u-calendar>

		<!-- 底部picker选择器 收件人 -->
		<u-picker mode="selector" v-model="isShowPickerAddressee" :default-selector="[0]" :range="selectorObj"
			:range-key="rangeKey" @confirm="showPickerChangeAddressee"></u-picker>
		<!-- 经办人下拉列表数据 -->
		<!-- 执行人弹出层 -->
		<UniPopup ref="UniPopup" @confrim="UniPopupConfrim" />
		<!-- 	<u-picker mode="selector" v-model="isShowPickerRealName" :default-selector="[0]" :range="selectorObjRealName"
			:range-key="rangeKeyRealName" @confirm="showPickerChangeRealName"></u-picker> -->
	</view>
</template>

<script>
	import {
		Cust_AddressBookGetDataListByMoreCondition,
		Base_ManageBase_UserGetDataList,
		SPL_SampleApplyMainSaveData
	} from '@/api/interface.js'
	// 引入执行人组件
	import UniPopup from "../../components/UniPopup.vue";
	//客户
	import Myuser from "../../components/OwnUser.vue";
	// 引入顶部navbar组件
	import HeaderTitle from '@/components/header/header-title.vue'
	import Product from "../../components/Product.vue";
	// // 引入公共头部组件
	// import HeaderMenu from "../../components/VolHeaderMenu.vue";
	// 应用工具函数
	export default {
		components: {
			Myuser,
			HeaderTitle,
			Product,
			UniPopup
		},

		data() {
			return {
				// 紧急程度下拉列表
				UrgencyOptions: [{
						value: '1',
						text: "一般"
					},
					{
						value: '2',
						text: "紧急"
					},
				],
				// 样品用途下拉数据
				PurposeOptions: [{
						value: '1',
						text: "自用"
					},
					{
						value: '2',
						text: "实验"
					},
				],
				// 右侧导航栏文字
				rightContent: "",
				rangeKey: "Addressee",
				rangeKeyRealName: "RealName",
				// 这种情况需要指定range-key为cateName，否则组件不知道该显示对象的哪个属性
				selectorObj: [], //收件人下拉列表数据
				selectorObjRealName: [], //经办人下拉列表数据
				// 是否展示底部picker选择起
				isShowPickerAddressee: false,
				isShowPickerRealName: false, //是否展示经办人下拉列表
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				hideshow: true, //显示或者隐藏footer
				// 手机格式校验
				telRules: [{
						required: true,
						message: "手机号不能为空",
						trigger: 'blur'
					},
					{
						validator: value => {
							console.log('是覅偶正确', value)
							// 手机号正则匹配 后续也可以用到该正则   /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/

							// 以下匹配电话号格式为010-88925890   ，  13847616463， 0731-85985051， 0312-5906070
							let regPhone1 = (/^(([0-9]{11})|([0-9]{4}\-[0-9]{8})|([0-9]{4}\-[0-9]{7}))$/)
							let regPhone2 = (/^(([0-9]{11})|([0-9]{3}\-[0-9]{8})|([0-9]{4}\-[0-9]{7}))$/)

							return regPhone1.test(value) || regPhone2.test(value);
						},
						message: "请输入正确的手机号格式",
						trigger: "onBlur"
					}
				],
				disabled: false,
				title: "新建",
				rightText: "",
				loading: false,
				finished: false,
				readonly: false,
				listClo: [],
				// 收件人列表
				columns: [],
				// 经办人列表
				columnsRealName: [],
				// 紧急程度
				columnsUrgency: [{
					Urgency: "一般"
				}, {
					Urgency: "紧急"
				}],
				columnsPurpose: [{
					Purpose: "自用"
				}, {
					Purpose: "实验"
				}],
				// 收件人弹窗
				showPicker: false,
				info: {},
				entity: {},
				data: [],
				show: false,
				showDate: false,
				pagination: {
					PageIndex: 1,
					PageRows: 10,
					Total: 0
				},
				Id: "",
				// 是否显示添加收件人按钮
				isAddButton: false,
				// 选中客户ID
				personID: "",
				// 样品用途弹窗
				showPickerPurpose: false,
				// 经办人弹窗
				showPickerRealName: false,
				// 紧急程度弹窗
				showPickerUrgency: false
			};
		},
		onShow() {


			// 获取收件人列表
			this.contactPerson()
			// 获取经办人列表
			this.getRealUserName();

			//默认赋值当前选择日期
			let time = this.$moment().format("YYYY-MM-DD");
			this.entity.ApplyDate = time

		},
		watch: {
			//监听显示高度
			// showHeight: function() {
			// 	if (this.docmHeight > this.showHeight) {
			// 		//隐藏
			// 		this.hideshow = false;
			// 	} else {
			// 		//显示
			// 		this.hideshow = true;
			// 	}
			// }
		},
		methods: {

			// 紧急程序下拉选择
			UrgencyOptionsChange(e) {
				console.log('紧急程度下拉选择', e)

			},
			// 添加收件人
			selectRightIconChange() {
				console.log('添加收件人', this.entity)
				uni.navigateTo({
					url: "/pages/CustAddress/CustAddress?CustomerId=" + this.entity.CustomerId
				})
			},
			// 获取经办人列表数据
			getRealUserName() {
				Base_ManageBase_UserGetDataList({}).then(res => {
					this.columnsRealName = res.Data.map(item => {
						return {
							value: item.Id,
							text: item.RealName
						}
					})
					console.log("获取经办人列表this.columnsRealName", this.columnsRealName);
				});
			},
			// 选择产品页面;
			AddProduct() {
				this.$refs.product.openForm();
			},

			//选中的产品
			Product(a) {
				a.forEach(item => {
					if (item.checked) {
						this.data.push({
							ProductId: item.cInvCode,
							cInvName: item.cInvName,
							cInvCode: item.cInvCode,
							cInvStd: item.cInvStd
						});
					}
				});
				console.log('选中的商品有', this.data)
			},



			// 样品产品列表加载
			onLoading() {
				if (this.$route.query.readonly == 1 || this.$route.query.readonly == 2) {
					this.loading = true; //防止第一页重复加载
					// 获取联系人列表数据
					this.getDataList();
				}
			},
			// 删除
			delte(Id, index) {
				if (Id[0]) {
					this.http
						.post("/SampleManagement/SPL_SampleApplyDetails/DeleteData", Id)
						.then(resJson => {
							Toast("删除成功");
							this.data.splice(index, 1);
							this.getDataList();
						});
				} else {
					this.data.splice(index, 1);
					Toast("操作成功");
				}
			},
			// 经办人点击事件
			showPickerClickRealName(item) {
				this.isShowPickerRealName = true
			},
			// 经办人弹窗确认事件
			onConfirmRealName(e) {
				// 关闭经办人弹窗
				this.showPickerRealName = false;
				console.log("经办人弹窗确定", this.entity, e);
				this.$set(this.entity, "RealName", e.RealName);
			},
			// 紧急程度弹窗确定事件
			onConfirmUrgency(e) {
				// 关闭紧急程度弹窗
				this.showPickerUrgency = false;
				this.$set(this.entity, "Urgency", e.Urgency);
			},
			// 样品用途弹窗确定事件
			onConfirmPurpose(e) {
				// 关闭样品用途弹窗
				this.showPickerPurpose = false;
				this.$set(this.entity, "Purpose", e.Purpose);
			},
			// 收件人确定按钮
			showPickerChangeAddressee(event, key) {
				this.entity.Addressee = this.selectorObj[event[0]].Addressee
			},
			// 经办人确定按钮
			showPickerChangeRealName(event, key) {
				this.entity.RealName = this.selectorObjRealName[event[0]].RealName
			},
			// 收件人点击事件
			showPickerClick() {
				this.show = true
				// 如果客户为空 提示
				if (!this.entity.CustomerName) {
					this.$errorToast("请先选择客户");
					return;
				}
				// 如果收件人列表为空 提示先添加收件人
				if (this.columns.length == 0) {
					this.$utils.showConfirm({
						content: '请先添加收件人信息',
						confirmText: "确定",
						confirmColor: "#2472C8"
					}).then(res => {
						if (res.confirm) {
							uni.redirectTo({
								url: '/pages/Login/Login',
							})
						} else {}
					})
				} else {
					console.log('收件人列表', this.columns)
					this.selectorObj = this.columns.map(item => {
						return {
							id: item.Id,
							Addressee: item.Addressee
						}
					})
					this.isShowPickerAddressee = true
				}
				// if (this.$route.query.Id) {
				// 	// 如果客户为空 提示
				// 	if (!this.entity.CustomerName) {
				// 		Toast("请先选择客户");
				// 		return;
				// 	}
				// 	// 如果收件人列表为空 提示先添加收件人
				// 	if (this.columns.length == 0) {
				// 		Dialog.alert({
				// 			message: "请先添加收件人信息",
				// 			confirmButtonColor: "#2472C8",
				// 			confirmButtonText: "确定"
				// 		}).then(() => {
				// 			// on close
				// 		});
				// 	} else {
				// 		// 显示收件人弹窗
				// 		this.showPicker = true;
				// 	}
				// } else {
				// 	// 如果客户为空 提示
				// 	if (!this.entity.CustomerName) {
				// 		Toast("请先选择客户");
				// 		return;
				// 	}
				// 	// 如果收件人列表为空 提示先添加收件人
				// 	if (this.columns.length == 0) {
				// 		Dialog.alert({
				// 			message: "请先添加收件人信息",
				// 			confirmButtonColor: "#2472C8",
				// 			confirmButtonText: "确定"
				// 		}).then(() => {
				// 			// on close
				// 		});
				// 	} else {
				// 		// 显示收件人弹窗
				// 		this.showPicker = true;
				// 	}
				// }
			},
			// 添加收件人按钮事件
			addPerson() {
				// 父组件直接通过refs获取子组件里的data变量赋值
				this.$refs.custAddress.fieldListParams.CustomerId = this.entity.CustomerId;
				// 打开添加收件人弹窗组件
				this.$refs.custAddress.openForm();
			},


			formatDate(date) {
				const time = new Date(date);
				const y = time.getFullYear();
				return `${y}-${date.getMonth() + 1}-${date.getDate()}`;
			},
			onConfirm(date) {
				this.showDate = false;
				this.entity.ApplyDate = this.formatDate(date);
			},
			//返回
			onClickLeft() {
				this.$router.go(-1);
				this.show = false;
			},



			//关闭
			close() {
				this.show = false;
				this.$router.go(-1);
			},
			//本条客户的数据
			Client(a) {
				// 先赋值选中的客户id
				this.personID = a.Id;
				this.$set(this.entity, "Addressee", "");
				this.$set(this.entity, "AddresseeTel", "");
				this.$set(this.entity, "ReceiveAddress", "");
				this.$set(this.entity, "CustomerName", a.cCusName);
				this.entity.CustomerId = a.Id || a.cCusCode;
				this.contactPerson(a.Id);
				// 选中客户后显示添加收件人按钮
				// this.isAddButton = true;
				this.rightContent = "添加收件人";
			},

			// 获取收件人信息列表
			contactPerson() {
				Cust_AddressBookGetDataListByMoreCondition({
						Search: [{
							Condition: "CustomerId",
							Keyword: this.personID
						}],
						...this.filters
					})
					.then(resJson => {
						this.columns = resJson.Data;
						this.listClo = resJson.Data;
					});
			},
			//选择客户
			CustomerChoice() {
				this.$refs.myuser.openForm();
				// if (!this.Id) {

				// }
			},
			// 获取样品详情
			getDataList() {
				if (this.$route.query.readonly == 0) {
					this.loading = false;
					return;
				}
				this.http
					.post("/SampleManagement/SPL_SampleApplyMain/GetTheDataOfAll", {
						PageIndex: this.pagination.PageIndex,
						PageRows: 10,
						SortField: "Id",
						SortType: "desc",
						Search: {
							Condition: "Id",
							Keyword: this.Id
						}
					})
					.then(res => {
						if (res.Success) {
							this.entity = res.Data;
							// 获取缓存里的登录账号名字realname
							let RealName = localStorage.getItem("RealName");
							this.$set(this.entity, "RealName", RealName ? RealName : "");
							if (res.Data.SSAD_List.length == 0) {
								// 停止加载
								this.loading = false;
								// 数据全部加载完成
								this.finished = true;
								return;
							}
							this.data = res.Data.SSAD_List;
							this.$set(
								this.entity,
								"ApplyDate",
								this.entity.ApplyDate ?
								this.entity.ApplyDate.substring(0, 10) :
								""
							);
							// 赋值客户id获取客户收件人列表
							// 赋值客户id获取客户收件人列表
							this.personID = this.entity.CustomerId;
							this.contactPerson();

							// 停止加载
							this.loading = false;
							// 数据全部加载完成
							this.finished = true;
						} else {
							// 停止加载
							this.loading = false;
							// 数据全部加载完成
							this.finished = true;
							Toast(res.Msg);
						}
					});
			},
			init() {
				this.Id = "";
				this.show = true;
				(this.data = []), (this.entity = {});
			},
			// 样品提交
			onSubmit() {
				var that = this
				// 判断是否有添加商品
				if (this.data.length == 0) {
					this.$utils.showConfirm({
						content: '请先添加产品',
						confirmText: "确定",
						confirmColor: "#2472C8"
					}).then(res => {
						if (res.confirm) {
							this.AddProduct();
						} else {}
					})
					return;
				}

				this.$set(this.entity, "Transactor", this.info.Id);
				var entityData = {
					...this.entity
				};
				var SSAD_List = [...this.data];
				entityData.SSAD_List = SSAD_List;
				console.log("开始提交了", entityData);

				this.$refs.form.validate().then(res => {
					this.loading = true
					uni.showLoading({
						title: '加载中'
					})
					SPL_SampleApplyMainSaveData(entityData)
						.then(resJson => {
							if (resJson.Success) {

								setTimeout(function() {
									that.$sucessToast('新建成功')
									that.loading = false
									uni.navigateBack()
									that.show = false;
									uni.hideLoading()
								}, 3000)
							} else {
								that.$errorToast()(resJson.Msg);
								that.show = false;
								that.loading = false
							}
						});
				}).catch(err => {})


			},
			openForm(Id) {
				this.init();
				if (Id) {
					this.Id = Id;
					this.getDataList();
				}
			}
		}
	};
</script>

<style scoped>
	.uni-easyinput>>>.uni-easyinput__content-textarea {
		height: 100rpx !important;
	}

	.scrollBox {
		margin-bottom: 130rpx;
		/* #ifdef H5 */
		height: calc(100vh - 440px);
		/* #endif */
		/* #ifdef APP */
		height: calc(100vh - 220px);
		/* #endif */
	}


	/* 适配底部导航栏 */
	.submitButton {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 170px;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(240rpx + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(240rpx + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		padding-top: 10px;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-left: 15px;
		padding-right: 15px;
	}


	.button {
		width: 100%;
		height: 36px;
		border-radius: 5px;
		background-color: rgb(19, 236, 70);
		color: #ffffff;
		font-size: 14px;
		outline: none;
		border: none;
	}

	/* 适配底部导航栏 */
	.page-bottom {
		position: fixed;
		bottom: 0;
		background-color: #ffffff;
		width: 91%;
		padding-left: 15px;
		padding-right: 15px;
		padding-top: 10px;
		height: 100px;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(88px + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(88px + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		/* left: 0;
  right: 0;

  height: 65px;
  height: calc(
    58px + constant(safe-area-inset-bottom)
  );
  height: calc(58px + env(safe-area-inset-bottom));
  background: #fff;
  padding: 10px 11px 0 20px;
  box-sizing: border-box;

  text-align: right;
  border-top: 1px solid #e9e9e9; */
	}

	/* 覆盖van-button的默认样式 */
	.van-button {
		height: 35px !important;
		border-radius: 5px;
	}

	.delete-list {
		display: flex;
		justify-content: flex-end;
		padding-right: 10px;
		margin-top: 8px;
	}

	.Fa {
		display: flex;
		justify-content: left;
	}

	.left {
		margin: 10px 0px 10px 15px;
	}

	.fontstepper {
		margin-left: 15px;
		line-height: 40px;
	}

	.font {
		margin-left: 15px;
		font-size: 14px;
	}

	.aa {
		text-align: right;
	}

	.scrollBar {
		box-sizing: border-box;
		/* height: 550px; */
		/* height: calc(100vh - 266px); */
		/* padding-bottom: 80px; */
		padding-bottom: 130px;
		/* overflow-y: auto; */
	}

	.scrollBar::-webkit-scrollbar {
		display: none;
	}

	.close {
		position: "absolute";

		right: 0;
		bottom: 0;
		padding: "5px 16px";
		background: "#fff";
		text-align: right;
		z-index: 1;
	}

	.client {
		box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
	}

	.mysamplebox {}

	/* .Father {
  display: flex;
} */
</style>
<style lang="less" scoped>
	// 覆盖vant-filed默认样式
	.textarea {
		padding: 0px 16px;

		::v-deep .van-field__label {
			width: 3rem;
		}
	}
</style>